import { bindEmail } from '@/api/flow/auth'

export default {
   data () {
    return {
      // form
      form: this.$form.createForm(this),

      // state
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false,
      },
    }
  },

  methods: {
    // send code email
    sendEmailCode () {
      const fields = ['email']
      const { first_name, last_name } = this.currentUser
      const data = {
        first_name,
last_name,
        ...this.form.getFieldsValue(fields),
      }
      this.sendCode(fields, data)
    },

    handleSubmit () {
      const { state } = this

      state.loginBtn = true

      return new Promise((resolve, reject) => {
        this.validateFieldsForm()
          .then(() => {
            this.submitForm()
              .then((data) => {
                resolve(data)
              })
              .catch((error) => {
                reject(error)
              })
              .finally(() => {
                state.loginBtn = false
              })
          })
          .catch((error) => {
            reject(error)
            state.loginBtn = false
          })
      })
    },

    submitCallBack () {
    },

    resetFields () {
      this.isSendCode = false

      this.form.resetFields()
    },

    // form validateFields
    validateFieldsForm () {
      return new Promise((resolve, reject) => {
        const {
          form: { validateFields },
        } = this

        const validateFieldsKey = ['email', 'code']

        validateFields(validateFieldsKey, { force: true, first: true }, (err, values) => {
          if (!err) {
            resolve()
            return false
          }
          reject(false)
        })
      })
    },

    // Retrieve password
    submitForm () {
      const validateFieldsKey = ['email', 'code']

      return new Promise((resolve, reject) => {
        const fields = this.form.getFieldsValue(validateFieldsKey)

        bindEmail(fields)
          .then((data) => {
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
  },
}
